<template>
  <div class="app-container" @scroll="scrollGet($event)" ref="DOM">
    <!-- 查询模块 -->
    <div class="formDiv">
    <el-form ref="form" :inline="true" :model="search_form" label-width="130px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="礼包名称:">
            <el-input v-model="search_form.name" name="name" placeholder="请输入礼包名称" clearable />
           </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="礼包内容:">
            <el-select v-model="search_form.comboType" placeholder="请选择" clearable>
              <el-option
                v-for="item in comboType_arr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上架状态:">
            <el-select v-model="search_form.status" placeholder="请选择上架状态" clearable>
              <el-option label="全部" value="-1" />
              <el-option label="上架" value="1" />
              <el-option label="下架" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24"/>
        <el-col :span="9">
          <el-form-item label="是否推送到美创家:">
            <el-select v-model="search_form.serverShow" placeholder="请选择" clearable>
              <el-option
                v-for="item in serverShow_arr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
           <el-form-item>
             <el-button type="primary" class="el-icon-search" @click="search" >查询</el-button>
             <el-button type="primary"  class="el-icon-refresh" @click="reset">重置</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24" />
          <el-col :span="24">
            <el-form-item style="float:right">
              <el-button type="primary" plain class="el-icon-plus" @click="add_goods">添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 列表 -->
    <div class="listDiv">
      <el-table v-loading="table_loading" :data="tableData" style="width: 100%">
        <!-- id -->
        <el-table-column fixed prop="sortWidget" label="排序" align="center" width="50" />
        <!-- 名称 -->
        <el-table-column fixed prop="name" label="礼包名称" align="center" :width="tableWidth" />
        <!-- 图片 -->
        <el-table-column label="礼包图片" align="center" :width="tableWidth">
          <template slot-scope="scope">
            <div>
              <img :src="common.img_url+scope.row.coverImage" alt class="smallBG" />
            </div>
          </template>
        </el-table-column>

        <!-- 礼包内容 -->
        <el-table-column label="礼包内容" align="center" :width="tableWidth">
          <template slot-scope="scope">
            <span v-if="scope.row.comboType == 0">正常购买</span>
            <span v-else>优惠券</span>
          </template>
        </el-table-column>

        <!-- 价格 -->
        <el-table-column prop="yprice" label="展示价" align="center" :width="tableWidth" />

        <!-- 价格 -->
        <el-table-column prop="price" label="售价" align="center" :width="tableWidth" />

        <!-- 上架状态 -->
        <el-table-column label="上架状态" align="center" :width="tableWidth">
          <template slot-scope="scope">
            <div>
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="changeSwitch($event,scope.row)"
              />
            </div>
          </template>
        </el-table-column>

        <!-- 推送状态 -->
        <el-table-column label="是否推送到美创家" align="center" :width="tableWidth">
          <template slot-scope="scope">
            <div>
              <el-switch
                v-model="scope.row.serverShow"
                :active-value="1"
                :inactive-value="0"
                @change="changeServerShow($event,scope.row)"
              />
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template slot-scope="scope">
            <!--            <el-button type="text" size="mini" @click="search_detail(scope.row)">查看</el-button>-->
            <el-button type="text" @click="editAdv(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteAdv(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加的页面 -->
    <add-goods
      v-if="showAddMask"
      :page_status="pageStatus"
      :is-hidden="showAddMask"
      :detail-info="detailInfo"
      :is_disabled="isDisabled"
      @checkMask="checkMask"
      @refresh="addOrUpdate"
    />

    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        :current-page="search_form.page"
        :page-sizes="[10,20,50,100]"
        :page-size="search_form.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>
<script>
import addGoods from "./add_goods";
import {
  deleteGoods,
  getGoodsList,
  updateGoods,
  updateGoodsServerShow,
  updateGoodsStatus,
} from "../../api/goods";
import { appType } from "../../utils/constanst";
export default {
  components: {
    addGoods,
  },
  data() {
    // 数据声明初始
    return {
      tableWidth: "200px",
      pageStatus: 1,
      adName: null,
      status: -1, // 商品状态 - -1显示全部  0下架 1上架
      search_form: {
        name: "",
        status: "",
        comboType:"",
        serverShow:"",
        page: 1,
        pageSize: 10,
      }, // 筛选条件
      serverShow_arr: [
        { value: -1, label: "全部" },
        { value: 1, label: "上架" },
        { value: 0, label: "下架" },
      ], //
      comboType_arr: [
        { value: 0, label: "正常购买" },
        { value: 1, label: "优惠券" },
      ], //
      showAddMask: false, // 是否显示添加弹窗
      total: 0,
      tableData: [], // 列表数据
      detailInfo: {}, // 详细信息-修改
      isDisabled: false, // 默认允许是否编辑
      table_loading: false,
      model: 0, // 0 初次加载   1表示条件筛选
      scrollTop: 0,
    };
  },
  // beforeRouteEnter(to, from, next) {
  //   console.log("切换", from);
  //   if (from.name == "/add_goods_new") {
  //     console.log("就是你");
  //     to.meta.isBack = true;
  //   }
  //   next();
  // },
  //新加路由保存参数
  beforeRouteLeave(to, from, next) {
    // const answer = window.confirm("当前页面搜索条件将会被保存");
    //更新 put
    let keyname = this.$route.name;
    let value = JSON.stringify(this.search_form);
    sessionStorage.setItem(keyname, value);

  let position = this.$el.scrollTop
  this.$store.commit('SAVE_POSITION', position) //离开路由时把位置存起来
    /*记住离开首页时页面滚动到的位置*/
    // this.scrollTop = this.$el.scrollTop;

    next();
  },

updated () {
  this.$nextTick(function(){
    console.log('this.$store.state',this.$store.state);
    let position = this.$store.state.user.position //返回页面取出来
    // window.scroll(0, position)
    this.$refs.DOM.scrollTo(0,position);
  })
},
  // 生命周期钩子，初始时获取数据
  mounted() {
    // 获取数据列表
    if (sessionStorage.getItem(this.$route.name)) {
      this.search_form = JSON.parse(sessionStorage.getItem(this.$route.name));
    }
    this.search();
  },
  // activated() {
  //   if (!this.$route.meta.isBack) {
  //     // 如果isBack是false，表明需要获取新数据，否则就不再请求，直接使用缓存的数据
  //     console.log("isBack是false");
  //     // this.search()
  //   } else {
  //     // if(this.scrollTop) {
  //     //恢复滚动条高度
  //     console.log("恢复滚动条高度", this.scrollTop);
  //     setTimeout(() => {
  //       // this.$el.scrollTop = this.scrollTop;
  //       console.log(
  //         document.getElementsByClassName("app-container")[0].scrollTop
  //       );
  //       document.getElementsByClassName("app-container")[0].scrollTop = 100;
  //     }, 100);
  //     // }
  //   }
  //   // 恢复成默认的false，避免isBack一直是true，导致下次无法获取数据
  //   this.$route.meta.isBack = false;
  // },
  methods: {
    scrollGet(e) {
      // const $el = this.$el;
      // this.scroll = this.$el.scrollTop;
      // console.log("this.$el.scrollTop", this.$el.scrollTop);
      // this.scrollTop = e.srcElement.scrollTop;
      //     var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      // console.log('scrollTop',scrollTop)
    },
    handleScroll() {
      //     console.log('ceshi');
      // var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      // console.log(scrollTop)
    },
    // 筛选
    search() {
      console.log('this.search_form.page',this.search_form.page)
      this.model = 1
      this.getGoods({
        name: this.search_form.name,
        status: isNaN(parseInt(this.search_form.status)) ? -1 : parseInt(this.search_form.status),
        comboType:this.search_form.comboType === "" ? null : this.search_form.comboType,
        serverShow:isNaN(parseInt(this.search_form.serverShow)) ? -1 : parseInt(this.search_form.serverShow),
        pageSize: this.search_form.pageSize,
        pageNum: this.search_form.page
      })

    },
    // 重置
    reset() {
      this.search_form.name = ''
      this.search_form.status = ''
      this.search_form.comboType = ''
      this.search_form.serverShow = ''
      this.getGoods()
    },
    // 获取数据列表
    getGoods(options = {
      pageSize: this.search_form.pageSize,
      pageNum: this.search_form.page,
      name: this.search_form.name,
      status: isNaN(parseInt(this.search_form.status)) ? -1 : parseInt(this.search_form.status),
      comboType:this.search_form.comboType === "" ? null : this.search_form.comboType,
      serverShow:isNaN(parseInt(this.search_form.serverShow)) ? -1 : parseInt(this.search_form.serverShow),
    }) {
      this.table_loading = true
      getGoodsList(options).then(res => {
        this.total = res.data.data.count
        // this.search_form.pageNum = res.data.data.pageNum
        // this.search_form.pageSize = res.data.data.pageSize
        this.tableData = res.data.data.list
        this.table_loading = false
      }).catch((error) => {
        this.table_loading = false
        this.$message.error('网络连接错误，请稍后再试')
      })
    },
    // 添加
    // showMask() {
    //   this.detailInfo = {} // 详细信息初始为空
    //   this.showAddMask = true // 显示添加弹窗
    //   this.pageStatus = 1
    // },
    //添加项目
    add_goods() {
      this.$router.push({
        path: "/add_goods_new",
        query: {
          page_status: 1,
        },
      });
    },
    // 编辑
    editAdv(row) {
      this.$router.push({
        path: "/add_goods_new",
        query: { id: row.id, goodsInfo: row, page_status: 2 },
      });
      // this.detailInfo = row // 赋值
      // this.isDisabled = false // 能否编辑
      // this.showAddMask = true // 显示添加弹窗
      // this.pageStatus = 2
    },
    // 查看详情
    search_detail(row) {
      console.log(row);
      this.$router.push({
        path: "/goods_detail",
        query: { id: row.id },
      });
    },
    // 删除
    deleteAdv(id) {
      this.$confirm("确认删除该套餐吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteGoods({
            id: id,
          })
            .then((result) => {
              const res = result.data;
              if (res.code === 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.search();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((err) => {
              this.$message.error("服务器网络错误，请稍后重试");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //关闭弹窗
    checkMask(isHidden) {
      this.detailInfo = {};
      this.showAddMask = isHidden;
    },
    //添加或更新
    addOrUpdate() {
      // 刷新列表
      this.search();
    },
    // 上架状态改变
    changeSwitch(status, item) {
      updateGoodsStatus({
        id: item.id,
        status: status,
      })
        .then((res) => {
          if (res.data.code === 0) {
            this.$message({
              message: "状态修改成功",
              type: "success",
            });
          } else {
            this.$message.error(res.data.msg);
          }
          // 刷新列表
          this.search();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 推送到服务端小程序状态改变
    changeServerShow(status, item) {
      updateGoodsServerShow({
        id: item.id,
        status: status,
      })
        .then((res) => {
          if (res.data.code === 0) {
            this.$message({
              message: "推送到服务端小程序状态修改成功",
              type: "success",
            });
          } else {
            this.$message.error(res.data.msg);
          }
          // 刷新列表
          this.search();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 当前页面改变
    handleCurrentChange(val) {
      this.search_form.page = val
      this.search()
    },
    //条数改变
    handleSizeChange(val) {
      this.search_form.pageSize = val
      this.search_form.page = 1
      this.search()
    },
  },
};
</script>
<style lang="less" scoped>
.app-container {
  padding: 20px !important;
  background: transparent;
  height: 100%;
  overflow-y: auto;
}
.formDiv {
  padding: 20px;
}
.listDiv {
  margin-bottom: 20px;
  padding: 0 20px;
}
.smallBG {
  width: 100px;
  height: 100px;
}
.block {
  text-align: right;
  margin-top: 20px;
}
</style>
